<template>
  <base-breadcrumb :title="title" :breadcrumb="!isAudit">
    <!-- QC活动成果 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 基本信息 -->
        <a-card :bordered="false" style="margin-bottom: 46px">
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :isEmit="false"
            :form="form"
            :editModel="editModel == 0 ? 'V' : ''"
            :formComponents="$refs"
            @selectOrg="selectOrg"
          >
            <!-- 课题名称 -->
            <template #topicName>
              <div v-if="editModel == 0" style="margin-top: -3px">{{ form.topicName }}</div>
              <a-row type="flex" align="middle" justify="space-between" style="flex-wrap: nowrap" v-else>
                <div style="width: 100%">
                  <BaseInput :value="form.topicName" disabled></BaseInput>
                </div>
                <ChooseQCActivityRegistration v-if="editModel != 0" :form="form" />
              </a-row>
            </template>
          </custom-form>
          <title-name title="相关附件" />
          <BTableUpload v-model="form.files" :disabled="editModel == 0" business-code="QM12" />
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div v-if="!isConsultation" class="btn_box tool-btns--fixed page-btn-right-top">
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >{{ statusCode === '2' || statusCode === '3' || form.changeVersion > 1 ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode === '0' || statusCode === '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode === '2')
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { qcActivityAchievement } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import ChooseQCActivityRegistration from '../components/ChooseQCActivityRegistration' // 选择QC课题注册信息

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    ChooseQCActivityRegistration
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      id: '', // 业务id
      historyId: '', // 履历id
      form: {
        branchComId: '',
        creatorName: '',
        viewName: ''
      }, // 表单
      statusCode: '', // 审批状态
      rules: {
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        activeYear: [{ required: true, message: '请选择活动实际开展年度', trigger: 'blur change' }],
        actualStartTime: [{ required: true, message: '请选择实际开始时间', trigger: 'change' }],
        actualEndTime: [{ required: true, message: '请选择实际结束时间', trigger: 'change' }],
        completeEmployeeIds: [{ required: true, message: '请选择课题实际完成人', trigger: 'change' }],
        topicName: [{ required: true, message: '请选择课题名称', trigger: 'change' }],
        trainTime: [{ required: true, message: '请填写质量培训时间', trigger: 'change' }]
      },
      yearOpen: false, // 年份显隐控件
      init: false, // 初始化标识
      titles: ['查看QC活动成果', '编辑QC活动成果', '新增QC活动成果', '变更QC活动成果'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      let args = {}
      if (this.businessId) {
        args.id = this.businessId
      } else {
        args.id = this.id
      }
      this.historyId && (args.historyId = this.historyId)
      qcActivityAchievement
        .getDetail(args)
        .then((res) => {
          this.loading[0] = false
          if (res.code === 200) {
            this.statusCode = res.data.statusCode // 审批状态
            // 若文件不存在则设置空数组
            !res.data.files && (res.data.files = [])
            // 若注册信息不存在则设置空对象
            if (res.data.register) {
              const formNames = [
                'topicName',
                'topicTypeName',
                'topicGroupCreationTime',
                'trainTime',
                'guidanceTypeName',
                'dutyName',
                'topicRegisterNumber'
              ]
              formNames.forEach((i) => {
                res.data[i] = res.data.register[i]
              })
              res.data.registerId = res.data.register.id
              delete res.data.register
            }
            res.data.departmentName = '技术质量部'
            // // 格式化课题实际完成人
            // res.data.editorEmployeeId &&
            //   res.data.completeEmployeeName &&
            //   this.$set(
            //     this.form,
            //     'completeEmployee',
            //     res.data.editorEmployeeId.map((item, idx) => ({
            //       key: item,
            //       label: res.data.completeEmployeeName[idx]
            //     }))
            //   )
            this.form = res.data
            this.form.viewName = this.form.branchComName + '/' + this.form.projectName
            this.$nextTick(() => {
              this.init = true
              if (this.editModel != 0) {
                this.form.creatorName = this.$userInfo()?.name // 默认填报人
              }
            })
          }
        })
        .catch(() => {
          this.loading[0] = false
        })
    } else {
      this.init = true
      this.form.creatorName = this.$userInfo()?.name // 默认填报人
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_qc_activity_achievement')
  },
  computed: {
    // 表单列表
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: this.editModel == 0 ? 8 : 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          statusSet: [1,2,3,4,5,6],
          disabled: this.editModel == 0,
          isNoBorder: this.editModel == 0,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   viewName: 'branchComName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     form: this.form,
        //     isMaintenance: true,
        //   }
        // },
        {
          keyName: 'activeYear',
          type: 'a-date-picker',
          attrs: {
            mode: 'year',
            valueFormat: 'YYYY',
            format: 'YYYY',
            open: this.yearOpen
          },
          label: '活动实际开展年度',
          change: () => {
            this.yearOpen = true
          },
          openChange: () => {
            this.yearOpen = true
          },
          panelChange: (value) => {
            this.yearOpen = false
            this.$set(this.form, 'activeYear', value.format?.('YYYY'))
            this.$refs['ruleForm'].clearValidate(['activeYear']);
          }
        },
        {
          keyName: 'actualStartTime',
          type: 'a-date-picker',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return this.form.actualEndTime && current && current > this.moment(this.form.actualEndTime).startOf('day')
            }
          },
          label: '实际开始时间'
        },
        {
          keyName: 'actualEndTime',
          type: 'a-date-picker',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return (
                this.form.actualStartTime && current && current < this.moment(this.form.actualStartTime).startOf('day')
              )
            }
          },
          label: '实际结束时间'
        },
        {
          keyName: 'completeEmployeeIds',
          type: 'SelectPerson',
          isInput: true,
          label: '课题实际完成人',
          idField: 'id',
          isEcho: true,
          personKeys: ['completeEmployeeIds', 'completeEmployeeName']
        },
        {
          slot: true,
          keyName: 'topicName',
          label: '课题名称'
        },
        {
          keyName: 'topicRegisterNumber',
          type: 'BaseInput',
          disabled: true,
          label: '课题注册号'
        },
        {
          keyName: 'topicTypeName',
          type: 'BaseInput',
          disabled: true,
          label: '课题类型'
        },
        {
          keyName: 'topicGroupCreationTime',
          type: 'BaseInput',
          disabled: true,
          label: '小组组建日期'
        },
        {
          keyName: 'trainTime',
          type: 'BaseInputNumber',
          // disabled: true,
          label: '质量管理小组人均培训时间',
          customRender(e) {
            return e ? e + 'h' : ''
          },
          attrs: {
            min: 1
          }
        },
        {
          keyName: 'guidanceTypeName',
          type: 'BaseInput',
          disabled: true,
          label: '指导者'
        },
        {
          keyName: 'dutyName',
          type: 'BaseInput',
          disabled: true,
          label: '课题负责人'
        },
        {
          keyName: 'departmentName',
          type: 'BaseInput',
          disabled: true,
          label: '质量管理部门'
        },
        {
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true,
          label: '创建人'
        }
      ]
    }
  },
  watch: {
    // 监听课题注册信息改变
    'form.registerId'(e) {
      if (e && this.init) {
        this.$refs.ruleForm.validateField('topicName')
      }
    },
    'form.trainTime'(e){
        e && this.$refs['ruleForm'].clearValidate(['trainTime']);
      }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null;
      let name = ['updatePost', 'handleCreate', 'adjustment'][that.editModel - 1] // 根据操作切换url地址
      const submit = () => {
        // 提交表单
        that.loading[statusCode] = true
        let form = that.$clone(that.form)
        form.fileLists = form.files?.map((i) => i.commonId)
        delete form.files
        form.statusCode = that.statusCode == '3' && statusCode == 0 ? that.statusCode : statusCode
        qcActivityAchievement[name](form)
          .then((res) => {
            if (res.code === 200 || res.data.code === 200) {
              that.loading[statusCode] = false
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
              if(statusCode*1===1) {
               //提交时，返回id
                  that.businessId = res.data.id;
                  that.setProcessConfig = this.processConfig;
                  return
              }else{
                that.$multiTab.close()
                }
            }
          })
          .catch(() => {
            that.loading[statusCode] = false
          })
      }
      // 若是草稿则无需校验表单
      if (statusCode === 0) {
        submit()
        return
      }
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
         this.submitApprovalConfirm(this.processConfig, (flag)=>{
           if(!flag) {
             return
           }
           submit()
         })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
